package com.bwie.goods.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Goods;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.GoodsReq;
import com.bwie.common.domain.response.GoodsQueryRes;
import com.bwie.common.domain.response.GoodsRes;
import com.bwie.common.utils.JwtUtils;
import com.bwie.goods.mapper.GoodsMapper;
import com.bwie.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;

    @Override
    public Goods findById(Integer goodsId) {
        return goodsMapper.findById(goodsId);
    }

    @Override
    public List<GoodsRes> goodsList(GoodsReq goodsReq) {
        //普通用户看自己 管理员看所有
        //获取用户的角色
        User user = userInfo();
        //判断角色
        if (user.getRole()==1){
            goodsReq.setCreateBy(user.getUserId());
        }
        return goodsMapper.goodsList(goodsReq);
    }

    @Override
    public void insert(Goods goods) {
        goodsMapper.insert(goods);
    }

    @Override
    public void update(Goods goods) {
        goodsMapper.update(goods);
    }

    @Override
    public void del(Integer goodsId) {
        goodsMapper.del(goodsId);
    }

    @Override
    public void batchDel(List<Integer> goodsIds) {
        goodsMapper.batchDel(goodsIds);
    }

    @Override
    public List<GoodsQueryRes> findAll() {
        return goodsMapper.findAll();
    }

    private User userInfo() {
        //获取请求头中的 token
        String token = request.getHeader(TokenConstants.TOKEN);
        //反向解析出userKey
        String userKey = JwtUtils.getUserKey(token);
        //获取用户信息
        String userJSONStr = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSONObject.parseObject(userJSONStr,User.class);
    }
}
